# Ionic Starter App
# angular.module is a global place for creating, registering and retrieving Angular modules
# 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
# the 2nd parameter is an array of 'requires'
# 'starter.controllers' is found in controllers.js

angular.module('upd-merchant', [
    'ionic'
    'wf-tab'
    'ui.router'
    'ionic.service.core'
    'templates'
    'constants'
    'ngStorage'
    'wf-log'
    'wf-config'
    'tab-home'
    'tab-market'
    'tab-myself'
    'tab-orders'
    'tab-purchase'
    'purchase-detail'
    'user'
    'utils'
    'personal-info'
    'order-detail'
    'wings-frog-directive'
    'goods-list'
    'email-bind'
    'shop-manage'
    'entrance'
    'goods-edit'
    'goods-detail'
    'ngCordova'
    'goods-add'
    'update-pwd'
    'warehouse-list'
    'message-list'
    'vip-list'
    'mall-info'
    'mall-logo'
    'mall-banner'
    'market-detail'
    'data-srv'
    'user-agreement-view'
    'about'
    'goods-addypk'
    'market-newproduct'
    'market-referencepro'
    'referencepro'
    'about-agreement'
    'Wx-public'
    'contact'
    'withdraw-cash'
    'withdraw-cash-form'
    'transaction-detail'
    'invoice-apply'
    'invoice-record'
    'market-contact'
    'address-list'
    'edit-address'
    'goods-search'
    'increase-account'
    'reset-overdraft'
    'province-data'
    'city-data'
    'sort-manage'
    'order-status'
    'send-modal'
    'gather-manage'
    'bank-account-list'
    'bank-account-edit'
    'sort-modal'
    'seller-address'
    'contact-way'
])

.run ($ionicPlatform, userData, $http, wxJsApi) ->
    $url = location.href
    $qIndex = $url.indexOf('?')
    $hashIndex = $url.indexOf('#')

    $urlArr = if $qIndex < $hashIndex then $url.substr($qIndex + 1,$hashIndex - $qIndex - 1).split('&') else $url.substr($qIndex + 1).split('&')

    $params = {}
    for $str in $urlArr
        $key = $str.split('=')[0]
        $value = $str.split('=')[1]
        $params[$key] = $value
    #获取token

    $ionicPlatform.ready ->

# Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
# for form inputs)
        if window.cordova and window.cordova.plugins.Keyboard
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar true

        # org.apache.cordova.statusbar required
        StatusBar.styleLightContent() if window.StatusBar


.config ($provide, userDataProvider, $httpProvider, backend, logDelegate) ->
    if backend
        httpDecorator = ($delegate)->
            return  (method, url, post, callback, headers, timeout, withCredentials) ->
                if method == 'POST'
                    headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=gb2312'
                if url != null && url != undefined && url.charAt(0) == '/'
                    if url != '/customer/login' and url != '/customer/register'
# 对于非登录/注册的接口，访问时加上用户token
                        apiToken = '7Wt1Vh2Cj6Nk8Sg1Ta3Sl1Sk5Tl5Kz4Y'
                        if url.indexOf('?') < 0 then url = url + "?apiToken=#{apiToken}"
                        else url = url + "&apiToken=#{apiToken}"
                    #                        token = userDataProvider.$get().getToken()
                    #                        if token != null
                    #                            url = url + "&userid=#{token}"
                    url = backend + url
                $delegate(method, url, post, callback, headers, timeout, withCredentials)
        $provide.decorator('$httpBackend', ["$delegate", httpDecorator])
    ua = navigator.userAgent.toLowerCase()
    if (/micromessenger/.test(ua)) # 如果是微信，使用浏览器提供的后退功能
        $provide.decorator '$ionicHistory', ($delegate) ->
            $delegate.goBack = (i) ->
                if i != undefined
                    window.history.go i
                else
                    window.history.back()
            $delegate
    $httpProvider.interceptors.push ($q, $rootScope) ->
        request: (config) ->
#            $rootScope.showLoading()
            config
        response: (response) ->
#            $rootScope.hideLoading()
            response
        responseError: (rejection) ->
#            $rootScope.hideLoading()
            $q.reject rejection

    $provide.decorator '$log', ['$delegate', logDelegate]

.config ($compileProvider) ->
    $compileProvider.imgSrcSanitizationWhitelist /^(https|http|file|blob|cdvfile):|data:image\//

.config ($stateProvider, $urlRouterProvider, $ionicConfigProvider) ->
    $ionicConfigProvider.platform.ios.tabs.style('standard')
    $ionicConfigProvider.platform.ios.tabs.position('bottom')
    $ionicConfigProvider.platform.android.tabs.style('standard')
    $ionicConfigProvider.platform.android.tabs.position('standard')
    $ionicConfigProvider.platform.ios.navBar.alignTitle('center')
    $ionicConfigProvider.platform.android.navBar.alignTitle('center')
    $ionicConfigProvider.platform.ios.backButton.previousTitleText('').icon('ion-ios-arrow-thin-left')
    $ionicConfigProvider.platform.android.backButton.previousTitleText('').icon('ion-android-arrow-back')
    $ionicConfigProvider.platform.ios.views.transition('ios')
    $ionicConfigProvider.platform.android.views.transition('android')


    $stateProvider

    .state('entrance',
        url: "/entrance"
        templateUrl: "templates/entrance/entrance.html"
        controller: "EntranceCtrl"
    )
    .state('login',
        url: "/login"
        templateUrl: "templates/user/login.html"
        controller: "LoginCtrl"
        params:
            origin: ''
    )
    .state('forgot-pwd',
        url: "/forgot-pwd"
        templateUrl: "templates/user/forgot-pwd.html"
        controller: "ForgotPwdCtrl"
    )
    .state('register',
        url: "/register"
        templateUrl: "templates/user/register.html"
        controller: "RegisterCtrl"
    )
    .state('user-agreement',
        url: '/user-agreement'
        templateUrl: 'templates/user-agreement/user-agreement.html'
        controller: 'userAgreementViewCtrl'
    )
    .state('tab',
        url: '/tab'
        template: '<ion-nav-view></ion-nav-view>'
        abstract: true
    )
    .state('tab.home',
        url: '/home'
        templateUrl: 'templates/tab-home/tab-home.html'
        controller: 'TabHomeCtrl'
    )
    .state('tab.orders',
        url: '/orders'
        templateUrl: 'templates/tab-orders/tab-orders.html'
        controller: 'TabOrdersCtrl'
    )
    .state('tab.purchase',
        url: '/purchase'
        templateUrl: 'templates/tab-purchase/tab-purchase.html'
        controller: 'TabPurchaseCtrl'
    )
    .state('tab.myself',
        url: '/myself'
        templateUrl: 'templates/tab-myself/tab-myself.html'
        controller: 'TabMyselfCtrl'
    )
    .state('tab.market-home',
        url: '/market'
        templateUrl: 'templates/tab-market/tab-market.html'
        controller: 'TabMarketCtrl'
    )
    .state('tab.market-orders',
        url: '/market'
        templateUrl: 'templates/tab-market/tab-market.html'
        controller: 'TabMarketCtrl'
    )
    .state('tab.market-purchase',
        url: '/market'
        templateUrl: 'templates/tab-market/tab-market.html'
        controller: 'TabMarketCtrl'
    )
    .state('tab.order-status-orders',
        url: '/order-status/:orderid'
        templateUrl: 'templates/order-status/order-status.html'
        controller: 'OrderStatusCtrl'
    )
    .state('tab.goods-list',
        url: '/goods-list'
        templateUrl: 'templates/goods-list/goods-list.html'
    )
    .state('tab.message-list-myself',
        url: '/message-list-myself'
        templateUrl: 'templates/message-list/message-list.html'
        controller: "MessageListCtrl"
    )
    .state('tab.message-list-home',
        url: '/message-list-home'
        templateUrl: 'templates/message-list/message-list.html'
        controller: "MessageListCtrl"
    )
    .state('tab.address-list',
        url: '/address-list'
        templateUrl: 'templates/address/address-list.html'
        controller: "AddressListCtrl"
    )
    .state('tab.edit-address-myself',
        url: '/edit-address-self'
        templateUrl: 'templates/address/edit-address.html'
        controller: "EditAddressCtrl"
        cache:false
        params:
            origin:{}
    )
    .state('tab.edit-address-orders',
        url: '/edit-address-orders'
        templateUrl: 'templates/address/edit-address.html'
        controller: "EditAddressCtrl"
        cache:false
        params:
            origin:{}
    )
    .state('tab.vip-list',
        url: '/vip-list'
        templateUrl: 'templates/vip-list/vip-list.html'
        controller: "VipListCtrl"
    )
    .state('tab.warehouse-list',
        url: '/warehouse-list'
        templateUrl: 'templates/warehouse-list/warehouse-list.html'
        controller: "WarehouseListCtrl"
    )
    .state('tab.gather-manage',
        url: '/gather-manage'
        templateUrl: 'templates/gather-manage/gather-manage.html'
        controller: "GatherManage"
    )
    .state('tab.bank-account-list',
        url: '/bank-account-list'
        templateUrl: 'templates/gather-manage/bank-account-list.html'
        controller: "BankAccountList"
    )
    .state('tab.bank-account-edit',
        url: '/bank-account-edit'
        templateUrl: 'templates/gather-manage/bank-account-edit.html'
        controller: "BankAccountEdit"
        params:
            account:{}
        cache:false
    )
    .state('tab.goods-detail',
        url: '/goods-detail/:goodId'
        templateUrl: 'templates/goods-detail/goods-detail.html'
        controller: "GoodsDetailCtrl"
    )
    .state('tab.goods-edit',
        url: '/goods-edit'
        templateUrl: 'templates/goods-edit/goods-edit.html'
        controller: "GoodsEditCtrl"
        cache: false
    )
    .state('tab.goods-add',
        url: '/goods-add'
        templateUrl: 'templates/goods-add/goods-add.html'
        controller: "GoodsAddCtrl"
    )
    .state('tab.shop-manage-home',
        url: '/shop-manage-home'
        templateUrl: 'templates/shop-manage/shop-manage.html'
        controller: "ShopManageCtrl"
    )
    .state('tab.shop-manage-myself',
        url: '/shop-manage-myself'
        templateUrl: 'templates/shop-manage/shop-manage.html'
        controller: "ShopManageCtrl"
    )
    .state('set-pwd',
        url: "/set-pwd"
        templateUrl: "templates/user/set-pwd.html"
        controller: "SetPwdCtrl"
    )
    .state('tab.personal-info',
        url: '/personal-info'
        templateUrl: 'templates/personal-info/personal-info.html'
        controller: "PersonalInfoCtrl"
    )

    .state('tab.update-pwd',
        url: '/update-pwd'
        templateUrl: 'templates/update-pwd/update-pwd.html'
        controller: "updatePwdCtrl"
        cache:false
    )
    .state('tab.mall-info-home',
        url: '/mall-info-home'
        templateUrl: 'templates/mall-info/mall-info.html'
        controller: "MallInfoCtrl"
    )
    .state('tab.mall-info-myself',
        url: '/mall-info-myself'
        templateUrl: 'templates/mall-info/mall-info.html'
        controller: "MallInfoCtrl"
    )
    .state('tab.email-bind',
        url: '/email-bind'
        templateUrl: 'templates/email-bind/email-bind.html'
        controller: "EmailBindCtrl"
    )
    .state('tab.contact-home',
        url: '/contact-home'
        templateUrl: 'templates/contact/contact.html'
        controller: "contactCtrl"
    )
    .state('tab.contact-myself',
        url: '/contact-myself'
        templateUrl: 'templates/contact/contact.html'
        controller: "contactCtrl"
    )

    .state('tab.order-detail',
        url: '/order-detail'
        templateUrl: 'templates/order-detail/order-detail.html'
        controller: "OrderDetailCtrl"
    )
    .state('tab.purchase-detail',
        url: '/purchase-detail'
        templateUrl: 'templates/purchase-detail/purchase-detail.html'
        controller: "PurchaseDetailCtrl"
        cache: false
    )
    .state('tab.mall-logo-home',
        url: "/mall-logo-home"
        templateUrl: "templates/mall-logo/mall-logo.html"
        controller: "MallLogoCtrl"
    )
    .state('tab.mall-logo-myself',
        url: "/mall-logo-myself"
        templateUrl: "templates/mall-logo/mall-logo.html"
        controller: "MallLogoCtrl"
    )
    .state('tab.mall-banner-home',
        url: "/mall-banner-home"
        templateUrl: "templates/mall-banner/mall-banner.html"
        controller: "MallBannerCtrl"
    )
    .state('tab.mall-banner-myself',
        url: "/mall-banner-myself"
        templateUrl: "templates/mall-banner/mall-banner.html"
        controller: "MallBannerCtrl"
    )
    .state('tab.market-detail',
        url: '/market-detail'
        templateUrl: 'templates/market-detail/market-detail.html'
        controller: 'MarketDetailCtrl'
    )
    .state('tab.withdraw-cash',
        url: '/withdraw-cash'
        templateUrl: 'templates/withdraw-cash/withdraw-cash.html'
        controller: 'withdrawCashCtrl'
    )
    .state('tab.withdraw-cash-form',
        url: '/withdraw-cash-form'
        templateUrl: 'templates/withdraw-cash-form/withdraw-cash-form.html'
        controller: 'withdrawCashFormCtrl'
    )
    .state('tab.invoice-apply',
        url: '/invoice-apply'
        templateUrl: 'templates/invoice-apply/invoice-apply.html'
        controller: 'invoiceApplyCtrl'
    )
    .state('tab.invoice-record',
        url: '/invoice-record'
        templateUrl: 'templates/invoice-record/invoice-record.html'
        controller: 'invoiceRecordCtrl'
    )
    .state('tab.transaction-detail',
        url: '/transaction-detail'
        templateUrl: 'templates/transaction-detail/transaction-detail.html'
        controller: 'transactionDetailCtrl'
    )
    .state('tab.about',
        url: "/about"
        templateUrl: "templates/about/about.html"
        controller: "AboutCtrl"
    )

    .state('tab.market-contact',
        url: "/market-contact"
        templateUrl: "templates/market-contact/market-contact.html"
        controller: "marketContactCtrl"
    )
    .state('tab.goods-addypk-home',
        url: "/goods-addypk"
        templateUrl: "templates/goods-addypk/goods-addypk.html"
        controller: "GoodsAddypkCtrl"
        params:
            obj: {}
        cache: false
    )
    .state('tab.goods-addypk-orders',
        url: "/goods-addypk"
        templateUrl: "templates/goods-addypk/goods-addypk.html"
        controller: "GoodsAddypkCtrl"
        params:
            obj: {}
        cache: false
    )
    .state('tab.goods-addypk-purchase',
        url: "/goods-addypk"
        templateUrl: "templates/goods-addypk/goods-addypk.html"
        controller: "GoodsAddypkCtrl"
        params:
            obj: {}
        cache: false
    )
    .state('tab.goods-addypk',
        url: "/goods-addypk"
        templateUrl: "templates/goods-addypk/goods-addypk.html"
        controller: "GoodsAddypkCtrl"
        params:
            obj: {}
        cache: false
    )
    .state('tab.market-newproduct',
        url: "/market-newproduct"
        templateUrl: "templates/market-newproduct/market-newproduct.html"
        controller: "newProductCtrl"
    )
    .state('tab.market-referencepro',
        url: "/market-referencepro"
        templateUrl: "templates/market-referencepro/market-referencepro.html"
        controller: "referenceproCtrl"
    )
    .state('tab.referencepro',
        url: "/referencepro"
        templateUrl: "templates/referencepro/referencepro.html"
        controller: "referProCtrl"
        cache: false
    )
    .state('tab.about-agreement',
        url: "/about-agreement"
        templateUrl: "templates/about-agreement/about-agreement.html"
        controller: "aboutAgreementCtrl"
    )
    .state('tab.Wx-public',
        url: "/Wx-public"
        templateUrl: "templates/Wx-public/Wx-public.html"
        controller: "WxPublicCtrl"
    )
    .state('tab.goods-search-home',
        url: "/goods-search-home/:currentItemId"
        templateUrl: "templates/goods-search/goods-search.html"
        controller: "GoodsSearchCtrl"
        cache:false
    )
    .state('tab.increase-account-home',
        url: "/increase-account-home"
        templateUrl: "templates/increase-account/increase-account.html"
        controller: "increaseAccountCtrl"
        params:
            vipItem:{}
        cache:false
    )
    .state('tab.reset-overdraft-home',
        url: "/reset-overdraft-home"
        templateUrl: "templates/reset-overdraft/reset-overdraft.html"
        controller: "resetOverdraftCtrl"
        params:
            vipItem:{}
        cache:false
    )
    .state('tab.seller-address',
        url: "/seller-address"
        templateUrl: "templates/seller-address/seller-address.html"
        controller: "SellerAddress"
        params:
            address:null
    )
    .state('tab.province-data-myself',
        url: '/province-data-myself'
        templateUrl: 'templates/areadata/province-data.html'
        controller: "provinceDataCtrl"
        params:
            origin:{}
    )
    .state('tab.province-data-orders',
        url: '/province-data-orders'
        templateUrl: 'templates/areadata/province-data.html'
        controller: "provinceDataCtrl"
        params:
            origin:{}
    )
    .state('tab.city-data-myself',
        url: '/city-data-myself'
        templateUrl: 'templates/areadata/city-data.html'
        controller: "cityDataCtrl"
        params:
            provinceData:{}
        cache:false
    )
    .state('tab.city-data-orders',
        url: '/city-data-orders'
        templateUrl: 'templates/areadata/city-data.html'
        controller: "cityDataCtrl"
        params:
            provinceData:{}
        cache:false
    )
    .state('tab.contact-way',
        url: '/contact-way'
        templateUrl: 'templates/contact-way/contact-way.html'
        controller: "ContactWay"
    )
    .state('tab.sort-manage',
        url: '/sort-manage'
        templateUrl: 'templates/sort-manage/sort-manage.html'
        controller: "sortManageCtrl"
    )
    $urlRouterProvider.otherwise '/entrance'

.run ($log, $state, userData, $rootScope, $ionicLoading, guid, wfConfig, $ionicPlatform, appVer, $ionicPopup, $ionicApp) ->
    $rootScope.showLoading = -> $ionicLoading.show()
    $rootScope.hideLoading = -> $ionicLoading.hide()

    $rootScope.$on '$stateChangeSuccess', ->
        stateName = $state.current.name
        hideTabs = not (stateName == 'tab.home' or stateName == 'tab.orders' or stateName == 'tab.myself' or stateName == 'tab.purchase')
        $rootScope.hideTabs = hideTabs

    $log.init 'upd-merchant', guid, wfConfig.loggerBackend, wfConfig.debug
    if userData.get()
        $state.go 'tab.home', {reload: true}
    autoUpdate = ->
        apply = ->
            document.getElementById("progress").style.display = "block"
            downloadProgress = 0
            IonicDeploy.download ((result) ->
                if result != 'true' && result != 'false'
                    downloadProgress = (result / 2)
                    document.getElementById("progress-text").innerHTML = "正在下载更新#{result}%..."
                    document.getElementById("progress-trunk").style.width = "#{result}%"
                else
                    IonicDeploy.extract ((result) ->
                        if result != 'done'
                            progress = downloadProgress + (result / 2)
                            document.getElementById("progress-text").innerHTML = "正在解压资源包#{result}%..."
                            document.getElementById("progress-trunk").style.width = "#{result}%"
                        else
                            IonicDeploy.redirect()
                    ), ((error) ->
                        $log.error "IonicDeploy - extrace failed: #{error}"
                        document.getElementById("progress").style.display = "none"
                        $ionicPopup.alert {title: '更新失败', template: '解压失败'}
                        $log.error error
                    )
            ), ((error) ->
                document.getElementById("progress").style.display = "none"
                $log.error "IonicDeploy - download failed: #{error}"
                $ionicPopup.alert {title: '更新失败', template: '下载失败'}
                $log.error error
            )
        IonicDeploy.check ((result) ->
            $log.log "IonicDeploy - check result: #{result}"
            if result.version == appVer
                apply() # update
        ), (err) ->
            $log.error "IonicDeploy - check failed: #{err}"
    $ionicPlatform.ready ->
        _.delay autoUpdate, 5 # 5秒后自动更新

.service 'tabData', ($rootScope, $ionicViewSwitcher) ->
    tabName = ['tab.home', 'tab.orders','tab.purchase', 'tab.myself']
    unwatch = $rootScope.$on '$stateChangeStart', (event, toState, toParams, fromState, fromParams)->
        if toState.name in tabName and fromState.name in tabName
            $ionicViewSwitcher.nextTransition 'none'
    [
        {state: 'tab.home', iconOn: 'wf-index-on', iconOff: 'wf-index-off', title: '首页'}
        {state: 'tab.purchase', iconOn: 'wf-purchase-on', iconOff: 'wf-purchase-off', title: '采购订单'}
        {state: 'tab.orders', iconOn: 'wf-order-on', iconOff: 'wf-order-off', title: '销售订单'}
        {state: 'tab.myself', iconOn: 'wf-my-on', iconOff: 'wf-my-off', title: '我'}
    ]

.run () ->
    Number.prototype.toFixed=  (d)->
# console.log Math.round(this * Math.pow(10,p))/Math.pow(10,p)
# return Math.round(this * Math.pow(10,p))/Math.pow(10,p) + ''
        s=this+""
        if !d then d=0
        if s.indexOf(".")==-1 then s+="."
        s+=new Array(d+1).join("0")
        if new RegExp("^(-|\\+)?(\\d+(\\.\\d{0,"+(d+1)+"})?)\\d*$").test(s)
            s="0"+RegExp.$2
            pm=RegExp.$1
            a=RegExp.$3.length
            b=true
            if a==d+2
                a=s.match(/\d/g)
                if parseInt(a[a.length-1])>4
                    for i in [a.length-2..0]
                        a[i]=parseInt(a[i])+1
                        if a[i]==10
                            a[i]=0
                            b=i!=1
                        else
                            break
                s=a.join("").replace(new RegExp("(\\d+)(\\d{"+d+"})\\d$"),"$1.$2")
            if b then s=s.substr(1)
            return (pm+s).replace(/\.$/,"")
        return this+""
